package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.IOException

@Composable
fun RegisterScreen(navController: NavController) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var password2 by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            TextField(
                value = username,
                onValueChange = { username = it },
                label = { Text("账号") },
                modifier = Modifier.fillMaxWidth()
            )
            TextField(
                value = password,
                onValueChange = { password = it },
                label = { Text("密码") },
                modifier = Modifier.fillMaxWidth()
            )
            TextField(
                value = password2,
                onValueChange = { password2 = it },
                label = { Text("密码") },
                modifier = Modifier.fillMaxWidth()
            )
            if (errorMessage.isNotEmpty()) {
                Text(
                    text = errorMessage,
                    color = androidx.compose.ui.graphics.Color.Red,
                    modifier = Modifier.padding(top = 8.dp)
                )
            }
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Button(
                    onClick = {
                        if (username.isNotBlank() && password.isNotBlank() && password2.isNotBlank()) {
                            if (password == password2) {
                                isLoading = true
                                errorMessage = ""

                                register(
                                    username, password, password2,
                                    onSuccess = {
                                        isLoading = false
                                        navController.navigate("main")
                                    },
                                    onError = { message ->
                                        isLoading = false
                                        errorMessage = message
                                    }
                                )
                            } else {
                                errorMessage = "两次输入的密码不一致"
                            }
                        } else {
                            errorMessage = "请填写所有必填字段"
                        }
                    },
                    enabled = !isLoading,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(text = if (isLoading) "注册中..." else "注册")
                }
                Button(
                    onClick = {
                        navController.navigate("login")
                    },
                    enabled = !isLoading,
                    modifier = Modifier.weight(1f)
                ) {
                    Text("返回")
                }
            }
        }
    }
}

fun register(
    user: String,
    pwd: String,
    pwd2: String,
    onSuccess: () -> Unit,
    onError: (String) -> Unit
) {
    val client = OkHttpClient()
    val json = """
        {
            "username": "$user",
            "password": "$pwd",
            "confirmPassword": "$pwd2"
        }
    """.trimIndent()

    val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
    val requestBody = RequestBody.create(mediaType, json)
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user/signUp")
        .post(requestBody)
        .build()
    CoroutineScope(Dispatchers.IO).launch {
        try {
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string()

            if (response.isSuccessful && responseBody != null) {
                val jsonObject = JSONObject(responseBody)
                val success = jsonObject.getBoolean("success")

                withContext(Dispatchers.Main) {
                    if (success) {
                        onSuccess()
                    } else {
                        val message = jsonObject.getString("message")
                        onError(message)
                    }
                }
            } else {
                withContext(Dispatchers.Main) {
                    onError("网络请求失败: ${response.code}")
                }
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                onError("注册异常: ${e.message}")
            }
        }
    }
}
